package com.chatgpt.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chatgpt.api.service.ChatRoleService;
import com.chatgpt.api.service.UserService;
import com.chatgpt.api.service.entity.ChatRole;
import com.chatgpt.api.service.entity.User;
import com.chatgpt.api.vo.ChatRoleVo;
import com.chatgpt.base.vo.BizVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/api/role")
public class ChatRoleController extends BaseController {

    private final ChatRoleService chatRoleService;
    private final UserService userService;

    public ChatRoleController(ChatRoleService chatRoleService, UserService userService) {
        this.chatRoleService = chatRoleService;
        this.userService = userService;
    }

    @GetMapping("/list")
    public BizVo list(HttpServletRequest request) {
        Integer userId = getIntParam(request, "user_id");
        QueryWrapper<ChatRole> queryWrapper = new QueryWrapper<>();
        if (userId > 0) {
            User user = userService.getById(userId);
            Object[] roleIds = user.getChatRoles().toArray();
            queryWrapper.in("marker", roleIds);
        }
        queryWrapper.orderByAsc("sort_num");
        List<ChatRole> roles = chatRoleService.list(queryWrapper);
        List<ChatRoleVo> vos = new ArrayList<>();
        for (ChatRole role : roles) {
            ChatRoleVo vo = new ChatRoleVo();
            BeanUtils.copyProperties(role, vo);
            vo.setCreatedAt(role.getCreatedAt().getTime() / 1000);
            vo.setUpdatedAt(role.getUpdatedAt().getTime() / 1000);
            vos.add(vo);
        }

        return BizVo.success(vos);
    }
}
